package service;

import dao.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import pojo.User;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Mapper 接口开发需要遵循以下规范：
 *
 * 1) Mapper.xml文件中的namespace与mapper接口的全限定名相同
 * 2) Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
 * 3) Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
 * 4) Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
 */
public class ServiceDemo {
    @Test
    public void userServiceTest() throws IOException {
        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = factory.openSession(true);
        //获取mapper，通过mybatis动态代理实现
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //执行mapper中定义的方法
        List<User> userList = mapper.findAll();
        System.out.println(userList);

        User user = mapper.findById(12);
        System.out.println(user);
    }
}
